package com.suray.wcs.web.system.controller;

import com.suray.basic.wcs.plc.entity.PlcDeviceDB;
import com.suray.basic.wcs.plc.service.impl.PlcDeviceDBServiceImpl;
import com.suray.commin.annotation.Log;
import com.suray.commin.core.controller.BaseController;
import com.suray.commin.core.controller.ResponseData;
import com.suray.commin.core.page.TableDataInfo;
import com.suray.commin.core.utils.SecurityUtils;
import com.suray.commin.core.utils.SpringContextHolder;
import com.suray.commin.core.utils.StringUtils;
import com.suray.commin.enmus.BusinessType;
import com.suray.commin.enmus.DeviceStatus;
import com.suray.wcs.service.init.SystemInit;
import com.suray.wcs.service.system.entity.PortDB;
import com.suray.wcs.service.system.service.IPortDBService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/port")
@CrossOrigin(value = "*", allowCredentials = "true")
public class PortDBController extends BaseController {
    @Autowired
    private IPortDBService portManService;
    private PlcDeviceDBServiceImpl plcDeviceDBService = SpringContextHolder.getBean(PlcDeviceDBServiceImpl.class);

    /**
     * 分页查询
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('port:query')")
    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/list")
    public TableDataInfo getPortList(PortDB portDB) {
        startPage();
        List<PortDB> result = portManService.selectList(portDB);
        for (PortDB db : result) {
            StringBuffer deviceStrs = new StringBuffer();
            if (StringUtils.isNotEmpty(db.getStations())) {
                for (String param : db.getStations().split("-")) {
                    long deviceId = Long.parseLong(param);
                    if (deviceId > 0) {
                        PlcDeviceDB plcdeviceDB = plcDeviceDBService.selectPlcDevById(deviceId);
                        if (plcdeviceDB == null) {
                            deviceStrs.append(param + ":未知设备->");
                        } else {
                            deviceStrs.append(plcdeviceDB.getDeviceName() + "->");
                        }
                    }
                }
            }
            if (StringUtils.isNotEmpty(deviceStrs)) {
                db.setStationStr(deviceStrs.delete(deviceStrs.lastIndexOf("-"), deviceStrs.length()).toString());
            }
        }
        return getDataTable(result);
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('port:edit')")
    @ApiOperation(value = "状态修改")
    @Log(title = "库口管理", method = "状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ResponseData changeStatus(@RequestBody PortDB portDB) {
        portDB.setUpdateBy(SecurityUtils.getUsername());
        PortDB portDB1 = SystemInit.PORTS.get(portDB.getPortId());
        portDB1.setStatus(portDB.getStatus());
        SystemInit.PORTS.put(portDB.getPortId(),portDB1);
        return toAjax(portManService.updatePortStatus(portDB));
    }

    /**
     * 新增库口
     *
     * @param portDB
     * @return
     */
    @PreAuthorize("@ss.hasPermi('port:add')")
    @ApiOperation(value = "新增库口")
    @Log(title = "库口管理", method = "新增库口", businessType = BusinessType.INSERT)
    @PostMapping(value = "/addPort")
    public ResponseData addPort(@Validated @RequestBody PortDB portDB) {
        if (portManService.checkPortCodeUnique(portDB)) {
            return ResponseData.error("新增库口'" + portDB.getPortName() + "'失败，交互编码已存在");
        }
        if (portDB.getPlcDeviceIds() != null) {
            StringBuffer setStationStr = new StringBuffer();
            for (int i = 0; i < portDB.getPlcDeviceIds().length; i++) {
                Long plcDeviceId = portDB.getPlcDeviceIds()[i];
                setStationStr.append(plcDeviceId + "-");
            }

            if (StringUtils.isNotEmpty(setStationStr)) {
                portDB.setStations(setStationStr.delete(setStationStr.lastIndexOf("-"), setStationStr.length()).toString());
            }
        }
        portDB.setCreateBy(SecurityUtils.getUsername());
        portDB.setCreateTime(new Date());
        boolean result = portManService.save(portDB);
        if (result) {
            SystemInit.PORTS.put(portDB.getPortId(),portDB);
        }
        return toAjax(result);
    }


    @PreAuthorize("@ss.hasPermi('port:query')")
    @ApiOperation(value = "获取库口")
    @GetMapping(value = "/getPort/{portId}")
    public ResponseData getPort(@PathVariable Integer portId) {
        PortDB portDB = portManService.getById(portId);
        if (portDB.getStations() != null){
            portDB.setPlcDeviceIds((Long[]) ConvertUtils.convert(portDB.getStations().split("-"), Long.class));
        }
        return ResponseData.success(portDB);
    }

    @PreAuthorize("@ss.hasPermi('port:query')")
    @ApiOperation(value = "获取库口")
    @GetMapping(value = "/getPortByModel/{portModel}")
    public ResponseData getPortByModel(@PathVariable Integer portModel) {
        return ResponseData.success(portManService.getByModel(portModel));
    }

    @PreAuthorize("@ss.hasPermi('port:edit')")
    @Log(title = "库口管理", method = "修改库口", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改库口")
    @PutMapping(value = "/updatePort")
    public ResponseData updatePortMan(@Validated @RequestBody PortDB portDB) {
        if (portManService.checkPortCodeUnique(portDB)) {
            return ResponseData.error("修改库口'" + portDB.getPortName() + "'失败，交互编码已存在");
        }
        if (portDB.getPlcDeviceIds() != null) {
            StringBuffer setStationStr = new StringBuffer();
            for (int i = 0; i < portDB.getPlcDeviceIds().length; i++) {
                Long plcDeviceId = portDB.getPlcDeviceIds()[i];
                setStationStr.append(plcDeviceId + "-");
            }

            if (StringUtils.isNotEmpty(setStationStr)) {
                portDB.setStations(setStationStr.delete(setStationStr.lastIndexOf("-"), setStationStr.length()).toString());
            }
        } else {
            portDB.setStations("") ;
        }
        SystemInit.PORTS.put(portDB.getPortId(),portDB);
        return toAjax(portManService.updateById(portDB));
    }

    @PreAuthorize("@ss.hasPermi('port:remove')")
    @Log(title = "库口管理", method = "删除库口", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除库口")
    @DeleteMapping(value = "/deletePort/{portIds}")
    public ResponseData deletePort(@PathVariable Long[] portIds) {
        for (Long portId : portIds) {
            PortDB byId = portManService.getById(portId);
            if (byId.getStatus().equals(DeviceStatus.OK.getCode())) {
                return ResponseData.error("库口:" + byId.getPortName() + "启用中不允许删除！");
            }
        }
        return toAjax(portManService.deletePortByIds(portIds));
    }
}
